<?php

namespace App\Http\Controllers\DingMaterial;

use App\Http\Controllers\Controller;
use App\Models\Dict;
use App\Models\Material\Material;
use App\Models\Material\OutMaterial;
use App\Models\Material\OutMaterialDetail;
use App\Models\Material\PutMaterial;
use App\Models\Material\PutMaterialDetail;
use App\Models\Material\TyreOutMaterial;
use App\Models\Material\TyreOutMaterialDetail;
use App\Models\Role;
use App\Models\Workflow\Workflow;
use App\Models\Workflow\WorkflowLog;
use App\Models\Workflow\WorkflowNode;
use App\Models\Workflow\WorkflowNodeProgram;
use App\Models\Workflow\WorkflowProcess;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class MaterialController extends Controller
{
    public $roleId;
    public $roleName;
    public $userId;
    public $ding;

    public function __construct()
    {
        $this->ding=new \App\Http\Controllers\DingSendNotifyController();
    }
    public function getSeeIds($userId)
    {
        if ($userId) {
            $userInfo = User::query()->where('ding_user_id', $userId)->first();
            if ($userInfo) {
                // $this->roleName = Role::where('id', $userInfo['group_id'])->first()->name;
                $this->roleId = DB::table('sys_roles_users')->where('user_id',
                    $userInfo['id'])->pluck('role_id')->toArray();
                $this->roleName = Role::query()->whereIn('id', $this->roleId)->pluck('name')->toArray();
                $this->userId = $userInfo['id'];
                $this->userName = $userInfo['name'];
            }
        }
    }

    /**
     * 经手人用户列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function getUser(Request $request)
    {
        $data = $request->all();
        $query = new Role;
        if (isset($data['role_name']) && $data['role_name'] == "维修") {
            $query = $query->where('name', '维修-维修厂');
        } else {
            $query = $query->where('name', '物资-经手人');
        }
        $role_id = $query->pluck('id')->toArray();
        $user_id = DB::table('sys_roles_users')->whereIn('role_id', $role_id)->pluck('user_id')->toArray();
        $data = User::query()->whereIn('id', $user_id)->get()->toArray();
        return response()->formatJson(['result' => $data]);
    }

    //获取钉钉token
    public function getToken()
    {
        $appKey = "dingltztbraha2fiyjsf";
        $appSecret = "2o1ifxGHVOSlzVzBVXse10K_rlBcwapJbjP77orbNSU6NYvGbk1XFPhxYOOgj70B";
        $url = 'https://oapi.dingtalk.com/gettoken?appkey='.$appKey.'&appsecret='.$appSecret;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($json, true);
        Cache::put('dingAccessToken', $arr['access_token'], 7200);
    }

    //获取钉钉用户信息
    public function userId(Request $request)
    {
        $data = $request->all();
        $appKey = "dingltztbraha2fiyjsf";
        $appSecret = "2o1ifxGHVOSlzVzBVXse10K_rlBcwapJbjP77orbNSU6NYvGbk1XFPhxYOOgj70B";
        $accessToken = Cache::get('dingAccessToken');
        if (! $accessToken) {
            $this->getToken();
            $accessToken = Cache::get('dingAccessToken');
        }

        $user_id_url = 'https://oapi.dingtalk.com/user/getuserinfo?access_token='.$accessToken.'&code='.$data['code'];
        $user_ids = $this->postCurl($user_id_url, [], 'get');
        $user_id = json_decode($user_ids, true);

        if ($user_id['errcode'] > 0) {
            return response()->json([
                'result' => ['errcode' => $user_id['errcode'], 'errmsg' => $user_id['errmsg']], 'ids' => false,
            ], 300);
        }
        // file_put_contents('22.txt',$user_ids.'^^^^'.date('Y-m-d H:i:s').'&&&'.$appKey.'%%%'.$appSecret);
        $url = 'https://oapi.dingtalk.com/user/get?access_token='.$accessToken.'&userid='.$user_id['userid'];
        $json = $this->postCurl($url, [], 'get');
        $arr = json_decode($json, true);

        if ($arr['errcode'] > 0) {
            return response()->json([
                'result' => ['errcode' => $arr['errcode'], 'errmsg' => $arr['errmsg']], 'ids' => false,
            ], 300);
        }
        // file_put_contents('33.txt',$json.'***'.$user_ids.'^^^^'.date('Y-m-d H:i:s'));
        Cache::put('userid', $arr['userid'], 7200);
        $user = DB::table('users')->where('phone', $arr['mobile'])->first();
        $role_id = DB::table('sys_roles_users')->where('user_id', $user['id'])->pluck('role_id')->toArray();
        $role_name = DB::table('sys_roles')->whereIn('id', $role_id)->pluck('name')->toArray();
        if ($user) {
            $result = DB::table('users')->where('phone', $arr['mobile'])->update(['ding_user_id' => $arr['userid']]);
        }
        return response()->json([
            'result' => $arr, 'ids' => $user ? $user['id'] : false,
            'role'   => ['role_id' => $role_id, 'role_name' => $role_name],
            'name'   => $user['name'],
        ], 200);
    }

    // curl
    public function postCurl($url, $data, $type)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, true);
            //设置post数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        $json = curl_exec($ch);
        curl_close($ch);
        return $json;
    }

    /**
     * 物资列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function materialList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getMaterialList($params)->get()->toArray();
        if ($data) {
            $data = $this->transData($data);
        }

        return response()->formatJson(['personnel' => $data]);
    }

    public function getMaterialList($params)
    {
        $query = DB::table('akbus_material');
        if (isset($params['type']) && $params['type'] === 'edit') {
            $query->where('amount', '>', 0);
        }
        if (isset($params['title'])) {
            $query->where('title', 'like', '%'.$params['title'].'%');
        }
        if (isset($params['supplier'])) {
            $query->where('supplier', 'like', '%'.$params['supplier'].'%');
        }
        $query->where('is_new', '!=', 1);
        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query->orderByDesc('created_at');
    }

    public function transData($data)
    {
        $units = Dict::getOptionsArrByName("物资单位");
        $count_total_price = 0;
        foreach ($data as $key => $v) {
            $data[$key]['unit_title'] = $v['unit'] !== null ? $units[$v['unit']] : '';
            $data[$key]['total_price'] = $v['amount'] * $v['price'];
            $count_total_price += $v['amount'] * $v['price'];
        }
        return $data;
    }

    /**
     * 获取数据字典
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function dictData(Request $request)
    {
        $params = $request->all();

        $result = Dict::getOptionsArrByName($params['title']);

        return response()->formatJson(['result' => $result]);
    }

    /**
     * 获取节点
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function workflowData(Request $request)
    {
        $params = $request->all();
        $result = Workflow::getOptionsArrByName($params['title']);

        return response()->formatJson(['result' => $result]);
    }

    /**
     * 获取线路车辆
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function lineBusNum(Request $request)
    {
        $params = $request->all();
        //每条线路
        $line = DB::table('akbus_bus_distribution')
            ->groupBy('line')->get()->toArray();
        $lineArr = [];
        $busArr = [];
        foreach ($line as $key => $v) {
            $lineArr[$key]['line'] = $v['line'];
            $busArr[$key]['line'] = $v['line'];
            $busArr[$key]['bus'] = DB::table('akbus_bus_distribution')
                ->where('line', $v['line'])->pluck('license_plate_num')->toArray();
        }

        return response()->formatJson(['line' => $lineArr, 'bus' => $busArr]);
    }

    /**
     * 获取物资详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function materialInfo(Request $request)
    {
        $params = $request->all();
        $data = Material::query()->where('id', $params['id'])
            ->first();
        return response()->formatJson(['result' => $data]);
    }

    /**
     * 删除物资
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function delMaterial(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $delCount = Material::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 物资库统计列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function materialStatiList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $query = $this->getMaterialStatiList($params);
        if (isset($params['date'])) {
            $date = date('Y-m-01', strtotime($params['date']));
        } else {
            $date = date('Y-m-01');
        }
        $materials_data = $query['materials_query']->get()->toArray();
        $material_balance_data = $query['material_balance_query']->get()->toArray();
        $put_data = $query['put_query']->get()->toArray();
        $out_data = $query['out_query']->get()->toArray();

        $result = $this->statiTransData([
            'materials'        => $materials_data,
            'put_data'         => $put_data,
            'out_data'         => $out_data,
            'material_balance' => $material_balance_data,
        ]);

        // $dataCount = $out_data->count();
        return response()->formatJson(['result' => $result, 'date' => $date]);
    }

    public function getMaterialStatiList($params)
    {
        $materials_query = DB::table('akbus_material');
        $material_balance_query = DB::table('akbus_material_balance');
        $put_query = DB::table('akbus_material_put_detail as d')
            ->leftJoin('akbus_workflow_process as w', 'w.apply_id', '=', 'd.put_id')
            ->select('d.created_at', 'd.material_id', 'd.amount')
            ->where('w.apply_key', 'akbus_material_put')
            ->where('w.status', 0);
        $out_query = DB::table('akbus_material_out_detail as d')
            ->leftJoin('akbus_workflow_process as w', 'w.apply_id', '=', 'd.out_id')
            ->select('d.bus_num', 'd.created_at', 'd.material_id', 'd.amount')
            ->where('w.apply_key', 'akbus_material_out')
            ->where('w.status', 0);
        $tyre_out_query = DB::table('akbus_material_tyre_out_detail as d')
            ->leftJoin('akbus_workflow_process as w', 'w.apply_id', '=', 'd.tyre_out_id')
            ->select('d.bus_num', 'd.created_at', 'd.material_id', 'd.amount')
            ->where('w.apply_key', 'akbus_material_tyre_out')
            ->where('w.status', 0);
        if (isset($params['date'])) {
            $time = strtotime($params['date']);
            $date = date('Y-m-01', $time);
        } else {
            $date = date('Y-m-01');
            $time = strtotime(date('Y-m-d'));
        }

        $firstday = date("Y-m-01", strtotime($date));
        $lastday = date("Y-m-d", strtotime("$firstday +1 month -1 day"));
        $material_balance_query->where('date', $lastday);
        $start_date = date('Y-m-26', strtotime(date('Y', $time).'-'.(date('m', $time) - 1).'-26'));
        $end_date = date('Y-m-25', strtotime(date('Y', $time).'-'.(date('m', $time)).'-25'));
        $put_query->where('d.created_at', '>=', $start_date);
        $put_query->where('d.created_at', '<=', $end_date);
        $out_query->where('d.created_at', '>=', $start_date);
        $out_query->where('d.created_at', '<=', $end_date);
        $tyre_out_query->where('d.created_at', '>=', $start_date);
        $tyre_out_query->where('d.created_at', '<=', $end_date);
        $out_query->union($tyre_out_query);
        if (isset($params['pageNumber']) && isset($params['pageSize'])) {
            $out_query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }
        return [
            'materials_query'        => $materials_query,
            'put_query'              => $put_query->orderByDesc('d.created_at'),
            'out_query'              => $out_query->orderByDesc('created_at'),
            'material_balance_query' => $material_balance_query,
        ];
    }

    public function statiTransData($data)
    {
        $units = Dict::getOptionsArrByName("物资单位");
        $materials = $data['materials'];
        $material_balance = $data['material_balance'];
        $put_data = $data['put_data'];
        $out_data = $data['out_data'];
        $result = [];
        foreach ($materials as $k => $v) {
            $result[$k]['title'] = $v['title'];
            $result[$k]['unit'] = $v['unit'] ? $units[$v['unit']] : '';
            $result[$k]['price'] = $v['price'];
            $result[$k]['put_data'] = [];
            $result[$k]['out_data'] = [];
            $result[$k]['balance_amount'] = '';
            foreach ($put_data as $pk => $pv) {
                if ($v['id'] === $pv['material_id']) {
                    $result[$k]['put_data'][$pk]['put_amount'] = $pv['amount'];
                    $result[$k]['put_data'][$pk]['put_created_at'] = $pv['created_at'];
                }
            }
            foreach ($out_data as $ok => $ov) {
                if ($v['id'] === $ov['material_id']) {
                    $result[$k]['out_data'][$ok]['bus_num'] = $ov['bus_num'];
                    $result[$k]['out_data'][$ok]['out_created_at'] = $ov['created_at'];
                    $result[$k]['out_data'][$ok]['out_amount'] = $ov['amount'];
                }
            }
            foreach ($material_balance as $bv) {
                if ($v['id'] === $bv['material_id']) {
                    $result[$k]['balance_amount'] = $bv['amount'];
                }
            }
        }
        $result_date = [];
        $num = 0;
        foreach ($result as $rv) {
            $out_count = count($rv['out_data']);
            $put_count = count($rv['put_data']);
            if ($out_count > 0) {
                $out_count_num = 0;
                foreach ($rv['out_data'] as $odk => $odv) {
                    $out_count_num++;
                    $result_date[$num]['out_count_num'] = $out_count_num;
                    $result_date[$num]['out_count'] = $out_count;
                    $result_date[$num]['title'] = $rv['title'];
                    $result_date[$num]['unit'] = $rv['unit'];
                    $result_date[$num]['price'] = $rv['price'];

                    $result_date[$num]['bus_num'] = $odv['bus_num'];
                    $result_date[$num]['out_created_at'] = $odv['out_created_at'];
                    $result_date[$num]['out_amount'] = $odv['out_amount'];
                    $result_date[$num]['balance_amount'] = $rv['balance_amount'];
                    $result_date[$num]['total_price'] = (int) $rv['balance_amount'] * (float) $rv['price'];

                    if (isset($rv['put_data'][$odk])) {
                        $result_date[$num]['put_amount'] = $rv['put_data'][$odk]['put_amount'];
                        $result_date[$num]['put_created_at'] = $rv['put_data'][$odk]['put_created_at'];
                    } else {
                        $result_date[$num]['put_amount'] = '';
                        $result_date[$num]['put_created_at'] = '';
                    }

                    $result_date[$num]['put_total_price'] = (int) $result_date[$num]['put_amount'] * (float) $rv['price'];
                    $result_date[$num]['curr_balance_amount'] = (int) $rv['balance_amount'] + (int) $result_date[$num]['put_amount'] - (int) $odv['out_amount'];
                    $num++;
                }
            } else {
                $result_date[$num]['out_count_num'] = 0;
                $result_date[$num]['out_count'] = $out_count;
                $result_date[$num]['title'] = $rv['title'];
                $result_date[$num]['unit'] = $rv['unit'];
                $result_date[$num]['price'] = $rv['price'];
                $result_date[$num]['bus_num'] = '';
                $result_date[$num]['out_created_at'] = '';
                $result_date[$num]['out_amount'] = '';
                $result_date[$num]['balance_amount'] = $rv['balance_amount'];

                $result_date[$num]['total_price'] = (int) $rv['balance_amount'] * (float) $rv['price'];
                if ($put_count > 0) {
                    foreach ($rv['put_data'] as $pdv) {
                        $result_date[$num]['put_amount'] = $pdv['put_amount'];
                        $result_date[$num]['put_created_at'] = $pdv['put_created_at'];
                    }
                } else {
                    $result_date[$num]['put_amount'] = '';
                    $result_date[$num]['put_created_at'] = '';
                }
                $result_date[$num]['put_total_price'] = (int) $result_date[$num]['put_amount'] * (float) $rv['price'];
                $result_date[$num]['curr_balance_amount'] = (int) $rv['balance_amount'] + (int) $result_date[$num]['put_amount'];
                $num++;
            }
        }
        return $result_date;
    }
    /****************************入库*******************************************/
    /**
     * 入库列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function putMaterialList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $countParams['status'] = $params['status'] = isset($params['status']) ? $params['status'] : '';
        $data = $this->getPutMaterialList($params)->get()->toArray();
        if ($data) {
            $data = $this->putTransData($data);
        }
        $this->getSeeIds($params['ding_user_id']);
        $group_id = $this->roleId;
        $role_name = $this->roleName;
        return response()->formatJson([
            'personnel' => $data, 'role' => $group_id, 'role_name' => $role_name,
        ]);
    }

    public function getPutMaterialList($params)
    {
        $this->getSeeIds($params['ding_user_id']);
        $group_id = $this->roleId;
        $nodes = DB::table('akbus_workflow_node')
            ->whereIn('role_id', $group_id)
            ->where('workflow_id', 3)
            ->pluck('node_key')
            ->toArray();
        $node_key = [];
        $node_ids = [];
        $status = [];
        if (count($nodes) > 0) {
            if (in_array("put_submit", $nodes)) {
                $node_key = array_merge($node_key,
                    ["put_submit", 'put_operator', 'put_custodian_warehouse', 'put_custodian', 'put_book']);
            }
            if (in_array("put_operator", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['put_operator']);
                        $status = array_merge($status, [2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key,
                            ['put_custodian_warehouse', 'put_custodian', 'put_book']);
                        $status = array_merge($status, [2, 0]);
                        $node_ids[] = 0;
                    } elseif ($params['status'] == 4) {
                        $node_key = array_merge($node_key, ['put_submit']);
                        $status = array_merge($status, [4]);
                    }
                }else {
                    $node_key = array_merge($node_key,
                        ['put_operator', 'put_custodian_warehouse', 'put_custodian', 'put_book']);
                    $status = array_merge($status, [2, 0]);
                    $node_ids[] = 0;
                }
                $params['handler_user_id'] = $this->userId;
            }
            if (in_array("put_custodian_warehouse", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['put_custodian_warehouse']);
                        $status = array_merge($status, [2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key, ['put_custodian', 'put_book']);
                        $status = array_merge($status, [2, 0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key,
                        ['put_custodian_warehouse', 'put_custodian', 'put_book']);
                    $status = array_merge($status, [2, 0]);
                    $node_ids[] = 0;
                }
            }
            if (in_array("put_custodian", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['put_custodian']);
                        $status = array_merge($status, [2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key, ['put_book']);
                        $status = array_merge($status, [2, 0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key, ['put_custodian', 'put_book']);
                    $status = array_merge($status, [2, 0]);
                    $node_ids[] = 0;
                }
            }
            if (in_array("put_book", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['put_book']);
                        $status = array_merge($status, [2]);
                    } elseif ($params['status'] == 3) {
                        $status = array_merge($status, [0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key, ['put_book']);
                    $status = array_merge($status, [2, 0]);
                    $node_ids[] = 0;
                }
            }
        } else {
            $node_key = array_merge($node_key,["put_submit", 'put_operator', 'put_custodian_warehouse', 'put_custodian', 'put_book']);
            $node_ids[] = 0;
            $status = array_merge($status,[1, 2, 0, 4]);
        }
        $node_ids = array_merge(
            $node_ids,
            DB::table('akbus_workflow_node')
                ->whereIn('node_key', array_unique($node_key))
                ->where('workflow_id', 3)
                ->pluck('id')
                ->toArray()
        );
        $node_ids = array_unique($node_ids);
        $status = array_unique($status);

        $query = DB::table('akbus_material_put as p')
            ->leftJoin('akbus_workflow_process as w', 'w.apply_id', '=', 'p.id')
            ->select(
                'p.title',
                'p.odd_num',
                'p.supplier',
                'p.user_id',
                'p.put_time',
                'w.node_id',
                'w.status',
                'w.reason',
                'p.id',
                'p.created_at'
            )
            ->where('w.apply_key', 'akbus_material_put');
        if (isset($params['odd_num'])) {
            $query->where('p.odd_num', 'like', '%'.$params['odd_num'].'%');
        }
        if (isset($params['odd_and_time'])) {
            $query->where('p.odd_num', 'like binary', '%'.$params['odd_and_time'].'%')
                ->orWhere('p.put_time', 'like binary', '%'.$params['odd_and_time'].'%')
                ->orWhere('p.title', 'like', '%'.$params['odd_and_time'].'%');
        }
        // if(isset($params['ding_user_id'])){
        //     $this->getSeeIds($params['ding_user_id']);
        //     $query->where('p.user_id', $this->userId);
        // }
        if (isset($node_ids)) {
            if (count($node_ids) > 0) {
                $query->whereIn('w.node_id', $node_ids);
            }
        }
        if (isset($status)) {
            if (count($status) > 0) {
                $query->whereIn('w.status', $status);
            }
        }
        if (isset($params['handler_user_id'])) {
            $query->where('p.handler_user_id', $params['handler_user_id']);
        }
        if (isset($params['pageNumber']) && isset($params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query->orderByDesc('p.created_at');
    }

    public function putTransData($data)
    {
        $state = Dict::getOptionsArrByName("申请单状态");
        $workflow_node = Workflow::getOptionsArrByName('入库申请单');
        foreach ($data as $key => $v) {
            $data[$key]['user_id'] = User::query()->where('id', $v['user_id'])->value('name');
            $data[$key]['status_title'] = $v['status'] ? $state[$v['status']] : '';
            if ($v['status'] === 1 || $v['status'] === 4) {
                $data[$key]['editDisabled'] = false;
                $data[$key]['editStyle'] = "color:#2d8cf0;font-size: 12px;";
                if ($v['status'] === 4) {
                    $data[$key]['delDisabled'] = true;
                } else {
                    $data[$key]['delDisabled'] = false;
                    $data[$key]['delStyle'] = "color:#2d8cf0;font-size: 12px;";
                }
            } else {
                $data[$key]['editDisabled'] = true;
                $data[$key]['delDisabled'] = true;
            }
            $data[$key]['addStyle'] = "color:#2d8cf0;font-size: 12px;";
            foreach ($workflow_node as $n) {
                if ($n['id'] === $v['node_id']) {
                    $data[$key]['process_node'] = $n['node_name'];
                }
            }
        }
        return $data;
    }

    /**
     * 添加入库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function addMaterial(Request $request)
    {
        $params = $request->all();
        $status = 1;
        if (isset($params['status'])) {
            $status = $params['status'];
        }
        $handler_user_id = User::query()->where('group_id', 6)->where('name', '李增贵')->first()->id;
        $total_put = PutMaterial::query()->where('created_at', 'like', date('Y-m-d').'%')->count();
        $putdetailList = $params['detailList'];
        $params['handler_user_id'] = $handler_user_id;
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['odd_num'] = date("YmdHis").'00'.($total_put + 1);
        $params['put_time'] = date('Y-m-d H:i:s', strtotime($params['put_time']));
        $this->getSeeIds($params['ding_user_id']);
        $params['title'] = '物资入库';
        $params['user_id'] = $this->userId;
        if (! isset($params['supplier'])) {
            $params['supplier'] = '';
        }
        unset($params['id'], $params['detailList'], $params['total_money'], $params['status'], $params['ding_user_id']);
        $put_id = PutMaterial::query()->insertGetId($params);
        if ($put_id) {
            foreach ($putdetailList as $v) {
                $m_amount = Material::query()->where('title', $v['title'])->where(
                    'supplier',
                    $params['supplier']
                )->where('price', $v['price'])->first();
                if (empty($m_amount)) {
                    $m['title'] = $v['title'];
                    $m['supplier'] = $params['supplier'];
                    $m['specs'] = $v['specs'] ?? '';
                    $m['unit'] = $v['unit'];
                    $m['amount'] = 0;
                    $m['price'] = $v['price'];
                    $m['is_new'] = 1;
                    $m['created_at'] = date('Y-m-d H:i:s');
                    $m_id = Material::query()->insertGetId($m);
                } else {
                    $m_id = $m_amount['id'];
                }
                unset($v['_index'], $v['_rowKey'], $v['index'], $v['total_price'], $v['unit_title'], $v['title'], $v['nameIndex'], $v['unitsIndex']);
                $v['put_id'] = $put_id;
                $v['material_id'] = $m_id;
                $v['created_at'] = date('Y-m-d H:i:s');
                PutMaterialDetail::query()->insertGetId($v);
            }

            //添加日志流程
            $pre_node_id = WorkflowNode::query()->where('node_key', 'put_submit')->value('id');
            $result_name='保存';
            if ($status == 2) {
                $node_id = WorkflowNodeProgram::query()->where('node_id', $pre_node_id)->where(
                    'result_key',
                    '<>',
                    'back'
                )->value('next_node_id');
                $description = '物资入库-'.$this->userName.PHP_EOL.
                                '单号：'.$params['odd_num'].PHP_EOL.
                                '时间：'.date('Y-m-d', strtotime($params['put_time']));
                $json=$this->ding->userNotify($node_id,'akbus_material_put',$put_id,$description);
                $result_name='提交';
            }else{
                $node_id = $pre_node_id;
            }
            WorkflowProcess::query()->insertGetId([
                'apply_id' => $put_id, 'apply_key' => 'akbus_material_put', 'node_id' => $node_id,
                'status'   => $status, 'created_at' => date('Y-m-d H:i:s'),
            ]);
            WorkflowLog::query()->insertGetId([
                'apply_id' => $put_id, 'apply_key' => 'akbus_material_put', 'node_id' => $pre_node_id,
                'status'   => $status,'result_name'=>$result_name, 'created_at' => date('Y-m-d H:i:s'),
            ]);
            $result = true;
        } else {
            $result = false;
        }
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 入库详情列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function putMaterialInfo(Request $request)
    {
        $params = $request->all();
        if (isset($params['id'])) {
            $result = PutMaterial::query()->where('id', $params['id'])->first();
            $state = Dict::getOptionsArrByName("申请单状态");
            $workflow_node = Workflow::getOptionsArrByName('入库申请单');
            $result['process'] = WorkflowProcess::query()->where('apply_id', $params['id'])
                ->where('apply_key', 'akbus_material_put')
                ->first();
            $processLog = WorkflowLog::query()->where('apply_id', $params['id'])
                ->where('apply_key', 'akbus_material_put')
                ->get()->toArray();
            foreach ($processLog as $k => $p) {
                foreach ($workflow_node as $w) {
                    if ($w['id'] == $p['node_id']) {
                        $processLog[$k]['node_id'] = $w['node_name'];
                    }
                }
                $processLog[$k]['status'] = $state[$p['status']];
            }
            $detailList = DB::table('akbus_material_put_detail as d')
                ->leftJoin('akbus_material as m', 'd.material_id', '=', 'm.id')
                ->select('d.id', 'd.specs', 'd.unit', 'd.amount', 'd.price', 'd.created_at', 'm.supplier', 'm.title')
                ->where('d.put_id', $result['id'])
                ->get()->toArray();
            $units = Dict::getOptionsArrByName("物资单位");
            foreach ($detailList as $key => $v) {
                $detailList[$key]['unit_title'] = $units[$v['unit']];
                $detailList[$key]['total_price'] = round($v['amount'] * $v['price'], 2);
            }
            $result['detailList'] = $detailList;
            $result['processLog'] = $processLog;
            $this->getSeeIds($params['ding_user_id']);
            $result['role_id'] = $this->roleId;
            $result['role_name'] = $this->roleName;
        } else {
            $result = [];
        }
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑入库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editMaterial(Request $request)
    {
        $params = $request->all();
        $id = $params['id'];
        if (isset($params['status'])) {
            $status = $params['status'];
        }
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['put_time'] = date('Y-m-d H:i:s', strtotime($params['put_time']));
        unset($params['id'], $params['detailList'], $params['total_money'], $params['status'], $params['ding_user_id']);
        $data = PutMaterial::query()->where('id', $id)->update($params);

        if (isset($status)) {
            //添加日志流程
            $node_id = WorkflowNode::query()->where('node_key', 'put_operator')->value('id');
            //发送消息通知
            $putInfo = PutMaterial::query()->where('id', $id)->first();
            $user_name = User::query()->where('id', $putInfo['user_id'])->value('name');
            $description = '物资入库-'.$user_name.PHP_EOL.
                            '单号：'.$putInfo['odd_num'].PHP_EOL.
                            '时间：'.date('Y-m-d', strtotime($putInfo['put_time']));
            $json=$this->ding->userNotify($node_id,'akbus_material_put',$id,$description);

            WorkflowLog::query()->insertGetId([
                'apply_id'   => $id, 'apply_key' => 'akbus_material_put', 'node_id' => 24, 'status' => $status,
                'result_name'=>'提交','created_at' => date('Y-m-d H:i:s'),
            ]);
            WorkflowProcess::query()->where('apply_id', $id)->where('apply_key', 'akbus_material_put')->update([
                'node_id' => $node_id, 'status' => $status, 'updated_at' => date('Y-m-d H:i:s'),
            ]);
        }
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑页添加入库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editAddPutMaterialDetail(Request $request)
    {
        $params = $request->all();
        if (isset($params['put_id'])) {
            $supplier = $params['supplier'];
            if (! isset($params['supplier'])) {
                $supplier = '';
            }
            $m_amount = Material::query()->where('title', $params['title'])->where(
                'supplier',
                $supplier
            )->where(
                'price',
                $params['price']
            )->first();
            if (empty($m_amount)) {
                $m['title'] = $params['title'];
                $m['supplier'] = $supplier;
                $m['specs'] = $params['specs'] ?? '';
                $m['unit'] = $params['unit'];
                $m['amount'] = 0;
                $m['is_new'] = 1;
                $m['price'] = $params['price'];
                $m['created_at'] = date('Y-m-d H:i:s');
                $m_id = Material::query()->insertGetId($m);
            } else {
                $m_id = $m_amount['id'];
            }
            unset($params['title'], $params['index'], $params['supplier']);
            $params['material_id'] = $m_id;
            $params['created_at'] = date('Y-m-d H:i:s');
            PutMaterialDetail::query()->insertGetId($params);
            $result = true;
        } else {
            $result = false;
        }
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑页删除入库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editDelPutMaterialDetail(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $delCount = PutMaterialDetail::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 编辑入库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editMaterialDetail(Request $request)
    {
        $params = $paramsResult = $request->all();
        $id = $params['id'];
        $supplier = '';
        if (isset($params['supplier'])) {
            $supplier = $params['supplier'];
        }
        $m_amount = Material::query()
            ->where('title', $params['title'])
            ->where('supplier', $supplier)
            ->where('price', $params['price'])
            ->first();
        if (empty($m_amount)) {
            $m['title'] = $params['title'];
            $m['supplier'] = $supplier;
            $m['specs'] = $params['specs'] ?? '';
            $m['unit'] = $params['unit'];
            $m['amount'] = 0;
            $m['is_new'] = 1;
            $m['price'] = $params['price'];
            $m['created_at'] = date('Y-m-d H:i:s');
            $m_id = Material::query()->insertGetId($m);
        } else {
            $m_id = $m_amount['id'];
        }
        $paramsResult['total_price'] = round($params['amount'] * $params['price'], 2);
        unset(
            $params['id'],
            $params['title'],
            $params['created_at'],
            $params['supplier'],
            $params['unit_title'],
            $params['total_price'],
            $params['_index'],
            $params['_rowKey']
        );
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['material_id'] = $m_id;
        $data = PutMaterialDetail::query()->where('id', $id)->update($params);
        $result = $paramsResult;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 删除入库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function delPutMaterial(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = $request['ids'];
            $detailList = PutMaterialDetail::query()->where('put_id', $ids)->delete();
            $delCount = PutMaterial::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     *入库，修改状态
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function toAuditPut(Request $request)
    {
        $params = $request->all();
        $id = $params['id'];
        $params['updated_at'] = date('Y-m-d H:i:s');
        $putMaterial = PutMaterial::query()->where('id', $id)->update(['updated_at' => date('Y-m-d H:i:s')]);
        $reason = "";
        if (isset($params['reason'])) {
            $reason = $params['reason'];
        }
        if ($params['status'] === 1 || $params['status'] === 4) {
            $node_id = 24;
        } else {
            $node_id = WorkflowNodeProgram::query()->where('node_id', $params['node_id'])->where(
                'result_key',
                '<>',
                'back'
            )->value('next_node_id');
            if ($node_id === 0) {
                $params['status'] = 0;
                $putdetailList = PutMaterialDetail::query()->where('put_id', $id)->get()->toArray();
                foreach ($putdetailList as $v) {
                    $m_amount = Material::query()->where('id', $v['material_id'])->first();
                    if (empty($m_amount)) {
                        $m['title'] = $v['title'];
                        $m['supplier'] = $params['supplier'];
                        $m['specs'] = isset($v['specs']) ? $v['specs'] : '';
                        $m['unit'] = $v['unit'];
                        $m['amount'] = (int) $v['amount'];
                        $m['price'] = $v['price'];
                        $m['is_new'] = 0;
                        $m['created_at'] = date('Y-m-d H:i:s');
                        Material::query()->insertGetId($m);
                    } else {
                        Material::query()->where('id', $v['material_id'])
                            ->update(['amount' => DB::Raw("amount+".(int) $v['amount']), 'is_new' => 0]);
                    }
                }
            }
        }
        //添加日志流程
        $data = WorkflowProcess::query()->where('apply_id', $id)->where('apply_key', 'akbus_material_put')->update([
            'node_id'    => $node_id, 'status' => $params['status'], 'reason' => $reason,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        // 4、记录流程日志
        $signature = isset($params['sign']) ? $params['sign'] : null;
        $result_name='审核';
        if($params['status'] == 1){
            $result_name='保存';
        }elseif($params['status'] == 2){
            if($params['node_id']==24){
                $result_name='提交';
            }else{
                $result_name='审核';
            }
        }elseif($params['status'] == 4){
            $result_name='审核不通过';
        }
        WorkflowLog::query()->insertGetId([
            'apply_id'  => $id, 'apply_key' => 'akbus_material_put', 'node_id' => $params['node_id'],
            'status'    => $params['status'],'result_name'=>$result_name, 'reason' => $reason, 'created_at' => date('Y-m-d H:i:s'),
            'signature' => $signature,
        ]);
        //发送消息通知
        $putInfo = PutMaterial::query()->where('id', $id)->first();
        $user_name = User::where('id', $putInfo['user_id'])->value('name');
        $description = '物资入库-'.$user_name.PHP_EOL.
                        '单号：'.$putInfo['odd_num'].PHP_EOL.
                        '时间：'.date('Y-m-d', strtotime($putInfo['put_time']));
        $json=$this->ding->userNotify($node_id,'akbus_material_put',$id,$description);
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }
    /****************************出入库详情*******************************************/
    /**
     * 详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function addMaterialDetail(Request $request)
    {
        $params = $request->all();
        $amount = 0;
        $price = 0;
        $unit = 0;
        if (isset($params['amount'])) {
            $amount = $params['amount'];
        }
        if (isset($params['price'])) {
            $price = $params['price'];
        }
        if (isset($params['unit'])) {
            $unit = $params['unit'];
        }
        $params['total_price'] = round((float) $amount * (float) $price, 2);
        $units = Dict::getOptionsArrByName("物资单位");
        $params['unit_title'] = $units[(int) $unit];
        // $params['is_consumables_name'] = $params['is_consumables'] === '1' ? '是' : '否';
        $params['created_at'] = date('Y-m-d H:i:s');
        $result = $params;
        return response()->formatJson(['result' => $result]);
    }
    /****************************出库*******************************************/
    /**
     * 出库列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function outMaterialList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $countParams['status'] = $params['status'] = isset($params['status']) ? $params['status'] : '';
        $data = $this->getOutMaterialList($params)->get()->toArray();
        if ($data) {
            $data = $this->outTransData($data);
        }
        $this->getSeeIds($params['ding_user_id']);
        $role_id = $this->roleId;
        $role_name = $this->roleName;
        return response()->formatJson([
            'personnel' => $data, 'role' => $role_id, 'role_name' => $role_name,
        ]);
    }

    public function getOutMaterialList($params)
    {
        $this->getSeeIds($params['ding_user_id']);
        $group_id = $this->roleId;
        $nodes = DB::table('akbus_workflow_node')
            ->whereIn('role_id', $group_id)
            ->where('workflow_id', 4)
            ->pluck('node_key')
            ->toArray();
        $node_key = [];
        $status = [];
        $node_ids = [];
        if (count($nodes) > 0) {
            if (in_array("out_submit", $nodes)) {
                $node_key = array_merge($node_key,
                    ['out_submit', 'out_operator', 'out_custodian_warehouse', 'out_custodian', 'out_book']);
            }
            if (in_array("out_operator", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['out_operator']);
                        $status = array_merge($status,[2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key,
                            ['out_custodian_warehouse', 'out_custodian', 'out_book']);
                        $status = array_merge($status,[2, 0]);
                        $node_ids[] = 0;
                    }
                } else {
                    $node_key = array_merge($node_key,
                        ['out_operator', 'out_custodian_warehouse', 'out_custodian', 'out_book']);
                    $status = array_merge($status,[2, 0]);
                    $node_ids[] = 0;
                }
                $params['handler_user_id'] = $this->userId;
            }
            if (in_array("out_custodian_warehouse", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['out_custodian_warehouse']);
                        $status = array_merge($status,[2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key, ['out_custodian', 'out_book']);
                        $status = array_merge($status,[2, 0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key,
                        ['out_custodian_warehouse', 'out_custodian', 'out_book']);
                    $status = array_merge($status,[2, 0]);
                    $node_ids[] = 0;
                }
            }
            if (in_array("out_custodian", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['out_custodian']);
                        $status = array_merge($status,[2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key, ['out_book']);
                        $status = array_merge($status,[2, 0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key, ['out_custodian', 'out_book']);
                    $status = array_merge($status,[2, 0]);
                    $node_ids[] = 0;
                }
            }
            if (in_array("out_book", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['out_book']);
                        $status = array_merge($status,[2]);
                    } elseif ($params['status'] == 3) {
                        $status = array_merge($status,[0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key, ['out_book']);
                    $status = array_merge($status,[2, 0]);
                    $node_ids[] = 0;
                }
            }
        } else {
            $node_key = array_merge($node_key,['out_submit', 'out_operator', 'out_custodian_warehouse', 'out_custodian', 'out_book']);
            $node_ids[] = 0;
            $status = array_merge($status,[1, 2, 0, 4]);
        }
        $node_ids = array_merge(
            $node_ids,
            DB::table('akbus_workflow_node')
                ->whereIn('node_key', array_unique($node_key))
                ->where('workflow_id', 4)
                ->pluck('id')
                ->toArray()
        );
        $node_ids = array_unique($node_ids);
        $status = array_unique($status);

        $query = DB::table('akbus_material_out as o')
            ->leftJoin('akbus_workflow_process as w', 'w.apply_id', '=', 'o.id')
            ->select(
                'o.title',
                'o.odd_num',
                'o.user_id',
                'o.out_time',
                'w.node_id',
                'w.status',
                'w.reason',
                'o.id',
                'o.created_at',
                DB::raw("DATE_FORMAT(o.out_time,'%Y-%m-%d') out_time_days")
            )
            ->where('w.apply_key', 'akbus_material_out');
        if (isset($params['odd_num'])) {
            $query->where('o.odd_num', 'like', '%'.$params['odd_num'].'%');
        }
        if (isset($params['odd_and_time'])) {
            $query->where('o.odd_num', 'like binary', '%'.$params['odd_and_time'].'%')
                ->orWhere('o.out_time', 'like binary', '%'.$params['odd_and_time'].'%')
                ->orWhere('o.title', 'like', '%'.$params['odd_and_time'].'%');
        }
        if (isset($params['handler_user_id'])) {
            $query->where('o.handler_user_id', $this->userId);
        }
        if (isset($node_ids)) {
            if (count($node_ids) > 0) {
                $query->whereIn('w.node_id', $node_ids);
            }
        }
        if (isset($status)) {
            if (count($status) > 0) {
                $query->whereIn('w.status', $status);
            }
        }
        if (isset($params['start_date_time'])) {
            $query->where('o.out_time', '>=', date('Y-m-d', strtotime($params['start_date_time'])));
        }
        if (isset($params['end_date_time'])) {
            $query->where('o.out_time', '<=', date('Y-m-d', strtotime($params['end_date_time'])));
        }
        if (isset($params['pageNumber']) && isset($params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query->orderByDesc('o.created_at');
    }

    public function outTransData($data)
    {
        $state = Dict::getOptionsArrByName("申请单状态");
        $workflow_node = Workflow::getOptionsArrByName('出库申请单');
        foreach ($data as $key => $v) {
            $data[$key]['user_id'] = User::query()->where('id', $v['user_id'])->value('name');
            $data[$key]['status_title'] = $v['status'] ? $state[$v['status']] : '';
            if ($v['status'] === 1 || $v['status'] === 4) {
                $data[$key]['editDisabled'] = false;
                $data[$key]['editStyle'] = "color:#2d8cf0;font-size: 12px;";
                if ($v['status'] === 4) {
                    $data[$key]['delDisabled'] = true;
                } else {
                    $data[$key]['delDisabled'] = false;
                    $data[$key]['delStyle'] = "color:#2d8cf0;font-size: 12px;";
                }
            } else {
                $data[$key]['editDisabled'] = true;
                $data[$key]['delDisabled'] = true;
            }
            $data[$key]['addStyle'] = "color:#2d8cf0;font-size: 12px;";
            foreach ($workflow_node as $n) {
                if ($n['id'] == $v['node_id']) {
                    $data[$key]['process_node'] = $n['node_name'];
                }
            }
        }
        return $data;
    }

    /**
     * 添加出库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function addOutMaterial(Request $request)
    {
        $params = $request->all();
        $status = $params['status'] ?? 1;
        $total_put = OutMaterial::query()->where('created_at', 'like', date('Y-m-d').'%')->count();
        $putdetailList = isset($params['detailList']) ? $params['detailList'] : [];
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['odd_num'] = date("YmdHis").'00'.($total_put + 1);
        $params['out_time'] = isset($params['out_time']) ?
            date('Y-m-d H:i:s', strtotime($params['out_time'])) :
            date('Y-m-d H:i:s');
        $this->getSeeIds($params['ding_user_id']);
        $params['user_id'] = $this->userId;
        $params['title'] = '物资出库';
        unset($params['id'], $params['detailList'], $params['total_money'], $params['status'], $params['ding_user_id']);
        $out_id = OutMaterial::query()->insertGetId($params);
        if ($out_id) {
            foreach ($putdetailList as $v) {
                unset($v['index'], $v['total_price'], $v['unit_title'], $v['title'], $v['title_id'], $v['_index'], $v['_rowKey'], $v['is_consumables_name'], $v['licenseIndex'], $v['lineIndex'], $v['nameIndex']);
                $v['out_id'] = $out_id;
                $v['created_at'] = date('Y-m-d H:i:s');
                OutMaterialDetail::query()->insertGetId($v);
            }
            //添加日志流程
            $pre_node_id = WorkflowNode::query()->where('node_key', 'out_submit')->value('id');
            $result_name='保存';
            if ($status == 2) {
                $node_id = WorkflowNodeProgram::query()->where('node_id', $pre_node_id)->where(
                    'result_key',
                    '<>',
                    'back'
                )->value('next_node_id');
                $description = '物资入库-'.$this->userName.PHP_EOL.
                                '单号：'.$params['odd_num'].PHP_EOL.
                                '时间：'.date('Y-m-d', strtotime($params['out_time']));
                $json=$this->ding->userNotify($node_id,'akbus_material_out',$out_id,$description);
                $result_name='提交';
            }else{
                $node_id = $pre_node_id;
            }
            WorkflowProcess::query()->insertGetId([
                'apply_id' => $out_id, 'apply_key' => 'akbus_material_out', 'node_id' => $node_id,
                'status'   => $status, 'created_at' => date('Y-m-d H:i:s'),
            ]);
            WorkflowLog::query()->insertGetId([
                'apply_id' => $out_id, 'apply_key' => 'akbus_material_out', 'node_id' => $pre_node_id,
                'status'   => $status,'result_name'=>$result_name, 'created_at' => date('Y-m-d H:i:s'),
            ]);
            $result = true;
        } else {
            $result = false;
        }
        // $result=$data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 出库详情列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function outMaterialInfo(Request $request)
    {
        $params = $request->all();
        if (isset($params['id'])) {
            $result = OutMaterial::query()->where('id', $params['id'])->first();
            $state = Dict::getOptionsArrByName("申请单状态");
            $workflow_node = Workflow::getOptionsArrByName('出库申请单');
            $result['process'] = WorkflowProcess::query()->where('apply_id', $params['id'])
                ->where('apply_key', 'akbus_material_out')
                ->first();
            $processLog = WorkflowLog::query()->where('apply_id', $params['id'])
                ->where('apply_key', 'akbus_material_out')
                ->get()->toArray();
            foreach ($processLog as $k => $p) {
                foreach ($workflow_node as $w) {
                    if ($w['id'] == $p['node_id']) {
                        $processLog[$k]['node_id'] = $w['node_name'];
                    }
                }
                $processLog[$k]['status'] = $state[$p['status']];
            }
            $detailList = DB::table('akbus_material_out_detail as d')
                ->leftJoin('akbus_material as m', 'd.material_id', '=', 'm.id')
                ->select(
                    'd.id',
                    'd.specs',
                    'd.material_id',
                    'd.is_consumables',
                    'd.unit',
                    'd.amount',
                    'd.price',
                    'd.created_at',
                    'd.line',
                    'd.bus_num',
                    'm.supplier',
                    'm.title'
                )
                ->where('d.out_id', $result['id'])
                ->get()->toArray();
            $units = Dict::getOptionsArrByName("物资单位");
            foreach ($detailList as $key => $v) {
                $detailList[$key]['unit_title'] = $units[$v['unit']];
                $detailList[$key]['total_price'] = $v['amount'] * $v['price'];
                $detailList[$key]['is_consumables_name'] = $v['is_consumables'] === 1 ? '是' : '否';
                $detailList[$key]['is_consumables'] = (string) $v['is_consumables'];
            }
            $result['detailList'] = $detailList;
            $result['processLog'] = $processLog;
            $this->getSeeIds($params['ding_user_id']);
            $result['role_id'] = $this->roleId;
            $result['role_name'] = $this->roleName;
        } else {
            $result = [];
        }
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑出库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editOutMaterial(Request $request)
    {
        $params = $request->all();
        $id = $params['id'];
        if (isset($params['status'])) {
            $status = $params['status'];
        }
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['out_time'] = date('Y-m-d H:i:s', strtotime($params['out_time']));
        unset($params['id'], $params['detailList'], $params['total_money'], $params['status'], $params['ding_user_id']);
        $data = OutMaterial::query()->where('id', $id)->update($params);

        if (isset($status)) {
            //添加日志流程
            $node_id = WorkflowNode::query()->where('node_key', 'out_operator')->value('id');
            //发送消息通知
            $putInfo = OutMaterial::query()->where('id', $id)->first();
            $user_name = User::query()->where('id', $putInfo['user_id'])->value('name');
            $description = '物资出库-'.$user_name.PHP_EOL.
                            '单号：'.$putInfo['odd_num'].PHP_EOL.
                            '时间：'.date('Y-m-d', strtotime($putInfo['out_time']));
            $json=$this->ding->userNotify($node_id,'akbus_material_out',$id,$description);

            WorkflowProcess::query()->where('apply_id', $id)->where('apply_key', 'akbus_material_out')->update([
                'node_id' => $node_id, 'status' => $status, 'updated_at' => date('Y-m-d H:i:s'),
            ]);
            WorkflowLog::query()->insertGetId([
                'apply_id'   => $id, 'apply_key' => 'akbus_material_out', 'node_id' => $node_id, 'status' => $status,
                'result_name'=>'提交','created_at' => date('Y-m-d H:i:s'),
            ]);
        }
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑出库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editOutMaterialDetail(Request $request)
    {
        $params = $paramsResult = $request->all();
        $id = $params['id'];
        $paramsResult['total_price'] = $params['amount'] * $params['price'];
        unset($params['id'], $params['title'], $params['created_at'], $params['supplier'], $params['unit_title'], $params['total_price'], $params['_index'], $params['_rowKey'], $params['is_consumables_name']);
        $params['updated_at'] = date('Y-m-d H:i:s');
        $data = OutMaterialDetail::query()->where('id', $id)->update($params);
        $result = $paramsResult;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑页添加出库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editAddOutMaterialDetail(Request $request)
    {
        $params = $request->all();
        if (isset($params['out_id'])) {
            $material_id = $params['title'];
            unset($params['title'], $params['index'], $params['supplier'], $params['unit_title']);
            $params['created_at'] = date('Y-m-d H:i:s');
            $params['material_id'] = $material_id;
            OutMaterialDetail::query()->insertGetId($params);
            $result = true;
        } else {
            $result = false;
        }
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 删除出库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function delOutMaterial(Request $request)
    {
        $result = false;
        if ($request->has('id')) {
            OutMaterialDetail::query()->where('out_id', $request['id'])->delete();
            $delCount = OutMaterial::destroy($request['id']);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 编辑页删除出库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editDelOutMaterialDetail(Request $request)
    {
        $result = false;
        if ($request->has('id')) {
            $delCount = OutMaterialDetail::destroy($request['id']);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     *出库，修改状态
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function toAuditOut(Request $request)
    {
        $params = $request->all();
        $id = $params['id'];
        $params['updated_at'] = date('Y-m-d H:i:s');
        $TyreOutMaterial = OutMaterial::query()->where('id', $id)->update(['updated_at' => date('Y-m-d H:i:s')]);
        $reason = "";
        if (isset($params['reason'])) {
            $reason = $params['reason'];
        }
        if ($params['status'] === 1 || $params['status'] === 4) {
            $node_id = 25;
        } else {
            $node_id = WorkflowNodeProgram::query()->where('node_id', $params['node_id'])->where(
                'result_key',
                '<>',
                'back'
            )->value('next_node_id');
            if ($node_id === 0) {
                $params['status'] = 0;
                $putdetailList = OutMaterialDetail::query()->where('id', $id)->get()->toArray();
                foreach ($putdetailList as $v) {
                    $m_amount = Material::query()->where('id', $v['material_id'])->first();
                    if (! empty($m_amount)) {
                        Material::query()->where('id', $v['material_id'])
                            ->update(['amount' => DB::Raw("amount-".(int) $v['amount'])]);
                    }
                }
            }
        }
        //添加日志流程
        $data = WorkflowProcess::query()->where('apply_id', $id)->where('apply_key', 'akbus_material_out')->update([
            'node_id'    => $node_id, 'status' => $params['status'], 'reason' => $reason,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        // 4、记录流程日志
        $signature = isset($params['sign']) ? $params['sign'] : null;
        $result_name='审核';
        if($params['status'] == 1){
            $result_name='保存';
        }elseif($params['status'] == 2){
            if($params['node_id']==25){
                $result_name='提交';
            }else{
                $result_name='审核';
            }
        }elseif($params['status'] == 4){
            $result_name='审核不通过';
        }
        WorkflowLog::query()->insertGetId([
            'apply_id'  => $id, 'apply_key' => 'akbus_material_out', 'node_id' => $params['node_id'],
            'status'    => $params['status'],'result_name'=>$result_name, 'reason' => $reason, 'created_at' => date('Y-m-d H:i:s'),
            'signature' => $signature,
        ]);
        //发送消息通知
        $putInfo = OutMaterial::query()->where('id', $id)->first();
        $user_name = User::query()->where('id', $putInfo['user_id'])->value('name');
        $description = '物资出库-'.$user_name.PHP_EOL.
                        '单号：'.$putInfo['odd_num'].PHP_EOL.
                        '时间：'.date('Y-m-d', strtotime($putInfo['out_time']));
        $json=$this->ding->userNotify($node_id,'akbus_material_out',$id,$description);
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 出库统计列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function outMaterialStatiList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getOutMaterialStatiList($params)
            ->groupBy('d.bus_num')->get()->toArray();
        if ($data) {
            $data = $this->outStatiTransData($data);
        }
        $dataCount = $this->getOutMaterialStatiList($countParams)->groupBy('d.bus_num')->groupBy('d.material_id')->count();
        //每条线路
        $line = DB::table('akbus_bus_distribution')
            ->groupBy('line')->get()->toArray();
        //物资名称
        $material = DB::table('akbus_material')->get()->toArray();
        return response()->formatJson([
            'result' => $data, 'count' => $dataCount, 'line' => $line, 'material' => $material,
        ]);
    }

    public function getOutMaterialStatiList($params)
    {
        $query = DB::table('akbus_material_out_detail as d')
            ->leftJoin('akbus_workflow_process as w', 'w.apply_id', '=', 'd.out_id')
            ->leftJoin('akbus_material as m', 'd.material_id', '=', 'm.id')
            ->select(
                'd.line',
                'bus_num',
                'd.specs',
                'd.unit',
                'd.price',
                'd.created_at',
                'm.title',
                DB::raw("SUM(d.amount) as total_amount")
            )
            ->where('w.apply_key', 'akbus_material_out')
            ->where('w.status', 0);
        if (isset($params['material'])) {
            if (gettype($params['material']) == 'string') {
                $params['material'] = explode(',', $params['material']);
            }
            if (count($params['material']) > 0) {
                $query->whereIn('d.material_id', $params['material']);
            }
        }
        if (isset($params['line']) && $params['line'] !== "-1") {
            $query->where('d.line', $params['line']);
        }
        if (isset($params['start_date_time'])) {
            $query->where('d.created_at', '>=', date('Y-m-d', strtotime($params['start_date_time'])));
        }
        if (isset($params['end_date_time'])) {
            $query->where('d.created_at', '<=', date('Y-m-d', strtotime($params['end_date_time'])));
        }
        if (isset($params['pageNumber']) && isset($params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }
        return $query->orderByDesc('d.created_at');
    }

    public function outStatiTransData($data)
    {
        $units = Dict::getOptionsArrByName("物资单位");
        // $state=Dict::getOptionsArrByName("申请单状态");
        foreach ($data as $key => $v) {
            $data[$key]['unit'] = $units[$v['unit']];
            $data[$key]['total_price'] = $v['price'] * $v['total_amount'];
        }
        return $data;
    }
    /****************************轮胎出库*******************************************/
    /**
     * 轮胎出库列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function tyreOutMaterialList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $countParams['status'] = $params['status'] = isset($params['status']) ? $params['status'] : '';
        $data = $this->getTyreOutMaterialList($params)->get()->toArray();
        if ($data) {
            $data = $this->tyreOutTransData($data);
        }
        $this->getSeeIds($params['ding_user_id']);
        $role_id = $this->roleId;
        $role_name = $this->roleName;
        return response()->formatJson([
            'personnel' => $data, 'role' => $role_id, 'role_name' => $role_name,
        ]);
    }

    public function getTyreOutMaterialList($params)
    {
        $this->getSeeIds($params['ding_user_id']);
        $role_id = $this->roleId;
        $nodes = DB::table('akbus_workflow_node')
            ->whereIn('role_id', $role_id)
            ->where('workflow_id', 5)
            ->pluck('node_key')
            ->toArray();
        $node_key = [];
        $status = [];
        $node_ids = [];
        if (count($nodes) > 0) {
            if (in_array("tyre_out_submit", $nodes)) {
                $node_key = array_merge($node_key,
                    [
                        "tyre_out_submit", 'tyre_out__operator', 'tyre_out_custodian_warehouse', 'tyre_out_custodian',
                        'tyre_out_book',
                    ]);
            }
            if (in_array("tyre_out__operator", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['tyre_out__operator']);
                        $status = array_merge($status,[2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key,
                            ['tyre_out_custodian_warehouse', 'tyre_out_custodian', 'tyre_out_book']);
                        $status = array_merge($status,[2, 0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key,
                        ['tyre_out__operator', 'tyre_out_custodian_warehouse', 'tyre_out_custodian', 'tyre_out_book']);
                    $status = array_merge($status,[2, 0]);
                    $node_ids[] = 0;
                }
                $params['handler_user_id'] = $this->userId;
            }
            if (in_array("tyre_out_custodian_warehouse", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['tyre_out_custodian_warehouse']);
                        $status = array_merge($status,[2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key,
                            ['tyre_out_custodian', 'tyre_out_book']);
                        $status = array_merge($status,[2, 0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key,
                        ['tyre_out_custodian_warehouse', 'tyre_out_custodian', 'tyre_out_book']);
                    $status = array_merge($status,[2, 0]);
                    $node_ids[] = 0;
                }
            }
            if (in_array("tyre_out_custodian", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['tyre_out_custodian']);
                        $status = array_merge($status,[2]);
                    } elseif ($params['status'] == 3) {
                        $node_key = array_merge($node_key, ['tyre_out_book']);
                        $status = array_merge($status,[2, 0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key,
                        ['tyre_out_custodian', 'tyre_out_book']);
                    $status = array_merge($status,[2, 0]);
                    $node_ids[] = 0;
                }
            }
            if (in_array("tyre_out_book", $nodes)) {
                if($params['status']&&$params['status']!=-1){
                    if ($params['status'] == 2) {
                        $node_key = array_merge($node_key, ['tyre_out_book']);
                        $status = array_merge($status,[2]);
                    } elseif ($params['status'] == 3) {
                        $status = array_merge($status,[0]);
                        $node_ids[] = 0;
                    }
                }else {
                    $node_key = array_merge($node_key, ['tyre_out_book']);
                    $status = array_merge($status,[2, 0]);
                    $node_ids[] = 0;
                }
            }
        } else {
            $node_key = array_merge($node_key,["tyre_out_submit", 'tyre_out__operator',
                                        'tyre_out_custodian_warehouse', 'tyre_out_custodian',
                                        'tyre_out_book',]);
            $node_ids[] = 0;
            $status = array_merge($status,[1, 2, 0, 4]);
        }
        $node_ids = array_merge($node_ids,
            DB::table('akbus_workflow_node')
                ->whereIn('node_key', array_unique($node_key))
                ->where('workflow_id', 5)
                ->pluck('id')
                ->toArray());
        $node_ids = array_unique($node_ids);
        $status = array_unique($status);

        $query = DB::table('akbus_material_tyre_out as o')
            ->leftJoin('akbus_workflow_process as w', 'w.apply_id', '=', 'o.id')
            ->select(
                'o.title',
                'o.odd_num',
                'o.fleet',
                'o.user_id',
                'o.out_time',
                'w.node_id',
                'w.status',
                'w.reason',
                'o.id',
                'o.created_at',
                DB::raw("DATE_FORMAT(o.out_time,'%Y-%m-%d') out_time_days")
            )
            ->where('w.apply_key', 'akbus_material_tyre_out');
        if (isset($params['odd_num'])) {
            $query->where('o.odd_num', 'like', '%'.$params['odd_num'].'%');
        }
        if (isset($params['odd_and_time'])) {
            $query->where('o.odd_num', 'like binary', '%'.$params['odd_and_time'].'%')
                ->orWhere('o.out_time', 'like binary', '%'.$params['odd_and_time'].'%')
                ->orWhere('o.title', 'like', '%'.$params['odd_and_time'].'%');
        }
        if (isset($params['handler_user_id'])) {
            $query->where('o.handler_user_id', $this->userId);
        }
        if (isset($node_ids)) {
            if (count($node_ids) > 0) {
                $query->whereIn('w.node_id', $node_ids);
            }
        }
        if (isset($status)) {
            if (count($status) > 0) {
                $query->whereIn('w.status', $status);
            }
        }
        if (isset($params['start_date_time'])) {
            $query->where('o.out_time', '>=', date('Y-m-d', strtotime($params['start_date_time'])));
        }
        if (isset($params['end_date_time'])) {
            $query->where('o.out_time', '<=', date('Y-m-d', strtotime($params['end_date_time'])));
        }
        if (isset($params['pageNumber']) && isset($params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query->orderByDesc('o.created_at');
    }

    public function tyreOutTransData($data)
    {
        $state = Dict::getOptionsArrByName("申请单状态");
        $workflow_node = Workflow::getOptionsArrByName('轮胎出库单');
        foreach ($data as $key => $v) {
            $data[$key]['user_id'] = User::query()->where('id', $v['user_id'])->value('name');
            $data[$key]['status_title'] = $v['status'] ? $state[$v['status']] : '';
            if ($v['status'] === 1 || $v['status'] === 4) {
                $data[$key]['editDisabled'] = false;
                $data[$key]['editStyle'] = "color:#2d8cf0;font-size: 12px;";
                if ($v['status'] === 4) {
                    $data[$key]['delDisabled'] = true;
                } else {
                    $data[$key]['delDisabled'] = false;
                    $data[$key]['delStyle'] = "color:#2d8cf0;font-size: 12px;";
                }
            } else {
                $data[$key]['editDisabled'] = true;
                $data[$key]['delDisabled'] = true;
            }
            $data[$key]['addStyle'] = "color:#2d8cf0;font-size: 12px;";
            foreach ($workflow_node as $n) {
                if ($n['id'] == $v['node_id']) {
                    $data[$key]['process_node'] = $n['node_name'];
                }
            }
        }
        return $data;
    }

    /**
     * 添加出库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function addTyreOutMaterial(Request $request)
    {
        $params = $request->all();
        $status = 1;
        if (isset($params['status'])) {
            $status = $params['status'];
        }
        $total_put = TyreOutMaterial::query()->where('created_at', 'like', date('Y-m-d').'%')->count();
        $putdetailList = $params['detailList'];
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['odd_num'] = date("YmdHis").'00'.($total_put + 1);
        $params['out_time'] = isset($params['out_time']) ? date('Y-m-d H:i:s',
            strtotime($params['out_time'])) : date('Y-m-d H:i:s');
        $this->getSeeIds($params['ding_user_id']);
        $params['user_id'] = $this->userId;
        $params['title'] = '物资轮胎出库';
        unset($params['id'], $params['detailList'], $params['total_money'], $params['status'], $params['ding_user_id']);
        $out_id = TyreOutMaterial::query()->insertGetId($params);
        if ($out_id) {
            foreach ($putdetailList as $v) {
                unset($v['index'], $v['total_price'], $v['unit_title'], $v['title'], $v['title_id'], $v['_index'], $v['_rowKey'], $v['licenseIndex'], $v['lineIndex'], $v['nameIndex']);
                $v['tyre_out_id'] = $out_id;
                TyreOutMaterialDetail::query()->insertGetId($v);
            }
            //添加日志流程
            $pre_node_id = WorkflowNode::query()->where('node_key', 'tyre_out_submit')->value('id');
            $result_name='保存';
            if ($status == 2) {
                $node_id = WorkflowNodeProgram::query()->where('node_id', $pre_node_id)->where(
                    'result_key',
                    '<>',
                    'back'
                )->value('next_node_id');
                $description = '物资入库-'.$this->userName.PHP_EOL.
                                '单号：'.$params['odd_num'].PHP_EOL.
                                '时间：'.date('Y-m-d', strtotime($params['out_time']));
                $json=$this->ding->userNotify($node_id,'akbus_material_tyre_out',$out_id,$description);
                $result_name='提交';
            }else{
                $node_id = $pre_node_id;
            }
            WorkflowProcess::query()->insertGetId([
                'apply_id' => $out_id, 'apply_key' => 'akbus_material_tyre_out', 'node_id' => $node_id,
                'status'   => $status, 'created_at' => date('Y-m-d H:i:s'),
            ]);
            WorkflowLog::query()->insertGetId([
                'apply_id' => $out_id, 'apply_key' => 'akbus_material_tyre_out', 'node_id' => $pre_node_id,
                'status'   => $status,'result_name'=>$result_name, 'created_at' => date('Y-m-d H:i:s'),
            ]);

            $result = true;
        } else {
            $result = false;
        }
        // $result=$data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑出库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editTyreOutMaterial(Request $request)
    {
        $params = $request->all();
        $id = $params['id'];
        if (isset($params['status'])) {
            $status = $params['status'];
        }
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['out_time'] = date('Y-m-d H:i:s', strtotime($params['out_time']));
        unset($params['id'], $params['detailList'], $params['total_money'], $params['status'], $params['ding_user_id']);
        $data = TyreOutMaterial::query()->where('id', $id)->update($params);
        if (isset($status)) {
            //添加日志流程
            $pre_node_id = WorkflowNode::query()->where('node_key', 'tyre_out_submit')->value('id');
            $result_name='保存';
            if ($status == 2) {
                $node_id = WorkflowNodeProgram::query()->where('node_id', $pre_node_id)->where(
                    'result_key',
                    '<>',
                    'back'
                )->value('next_node_id');
                //发送消息通知
                $putInfo = TyreOutMaterial::query()->where('id', $id)->first();
                $user_name = User::query()->where('id', $putInfo['user_id'])->value('name');
                $description = '物资轮胎出库-'.$user_name.PHP_EOL.
                                '单号：'.$putInfo['odd_num'].PHP_EOL.
                                '时间：'.date('Y-m-d', strtotime($putInfo['out_time']));
                $json=$this->ding->userNotify($node_id,'akbus_material_tyre_out',$id,$description);
                $result_name='提交';

            }
            WorkflowLog::query()->insertGetId([
                'apply_id' => $id, 'apply_key' => 'akbus_material_tyre_out', 'node_id' => $pre_node_id,
                'status'   => $status,'result_name'=>$result_name, 'created_at' => date('Y-m-d H:i:s'),
            ]);
            WorkflowProcess::query()->where('apply_id', $id)->where('apply_key', 'akbus_material_tyre_out')->update([
                'node_id' => $node_id, 'status' => $status, 'updated_at' => date('Y-m-d H:i:s'),
            ]);
        }
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 轮胎出库详情列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function tyreOutMaterialInfo(Request $request)
    {
        $params = $request->all();
        if (isset($params['id'])) {
            $result = TyreOutMaterial::query()->where('id', $params['id'])->first();
            $state = Dict::getOptionsArrByName("申请单状态");
            $workflow_node = Workflow::getOptionsArrByName('轮胎出库单');
            $result['process'] = WorkflowProcess::query()->where('apply_id', $params['id'])
                ->where('apply_key', 'akbus_material_tyre_out')
                ->first();
            $processLog = WorkflowLog::query()->where('apply_id', $params['id'])
                ->where('apply_key', 'akbus_material_tyre_out')
                ->get()->toArray();
            foreach ($processLog as $k => $p) {
                foreach ($workflow_node as $w) {
                    if ($w['id'] == $p['node_id']) {
                        $processLog[$k]['node_id'] = $w['node_name'];
                    }
                }
                $processLog[$k]['status'] = $state[$p['status']];
            }
            $detailList = DB::table('akbus_material_tyre_out_detail as d')
                ->leftJoin('akbus_material as m', 'd.material_id', '=', 'm.id')
                ->select(
                    'd.id',
                    'd.line',
                    'd.bus_num',
                    'd.specs',
                    'd.material_id',
                    'd.unit',
                    'd.amount',
                    'd.price',
                    'd.created_at',
                    'm.supplier',
                    'm.title'
                )
                ->where('d.tyre_out_id', $result['id'])
                ->get()->toArray();
            $units = Dict::getOptionsArrByName("物资单位");
            foreach ($detailList as $key => $v) {
                $detailList[$key]['unit_title'] = $units[$v['unit']];
                $detailList[$key]['total_price'] = $v['amount'] * $v['price'];
            }
            $result['detailList'] = $detailList;
            $result['processLog'] = $processLog;
            $this->getSeeIds($params['ding_user_id']);
            $result['role_id'] = $this->roleId;
            $result['role_name'] = $this->roleName;
        } else {
            $result = [];
        }
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑轮胎出库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editTyreOutMaterialDetail(Request $request)
    {
        $params = $paramsResult = $request->all();
        $id = $params['id'];
        $paramsResult['total_price'] = $params['amount'] * $params['price'];
        unset($params['id'], $params['title'], $params['created_at'], $params['supplier'], $params['unit_title'], $params['total_price'], $params['_index'], $params['_rowKey']);
        $params['updated_at'] = date('Y-m-d H:i:s');
        TyreOutMaterialDetail::query()->where('id', $id)->update($params);
        $result = $paramsResult;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 编辑页添加轮胎出库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editAddTyreOutMaterialDetail(Request $request)
    {
        $params = $request->all();
        if (isset($params['tyre_out_id'])) {
            $material_id = $params['title'];
            unset($params['title'], $params['index'], $params['supplier'], $params['unit_title']);
            $params['created_at'] = date('Y-m-d H:i:s');
            $params['material_id'] = $material_id;
            TyreOutMaterialDetail::query()->insertGetId($params);
            $result = true;
        } else {
            $result = false;
        }
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 删除轮胎出库
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function delTyreOutMaterial(Request $request)
    {
        $result = false;
        if ($request->has('id')) {
            TyreOutMaterialDetail::query()->where('tyre_out_id', $request['id'])->delete();
            $delCount = TyreOutMaterial::destroy($request['id']);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 编辑页删除轮胎出库详情
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function editDelTyreOutMaterialDetail(Request $request)
    {
        $result = false;
        if ($request->has('id')) {
            $delCount = TyreOutMaterialDetail::destroy($request['id']);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     *轮胎出库，修改状态
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function toAuditTyreOut(Request $request)
    {
        $params = $request->all();
        $id = $params['id'];
        $params['updated_at'] = date('Y-m-d H:i:s');
        $TyreOutMaterial = TyreOutMaterial::query()->where('id', $id)->update(['updated_at' => date('Y-m-d H:i:s')]);
        $reason = "";
        if (isset($params['reason'])) {
            $reason = $params['reason'];
        }
        if ($params['status'] == 1 || $params['status'] == 4) {
            $node_id = 26;
        } else {
            $node_id = WorkflowNodeProgram::query()->where('node_id', $params['node_id'])->where(
                'result_key',
                '<>',
                'back'
            )->value('next_node_id');
            if ($node_id === 0) {
                $params['status'] = 0;
                $putdetailList = TyreOutMaterialDetail::query()->where('id', $id)->get()->toArray();
                foreach ($putdetailList as $v) {
                    $m_amount = Material::query()->where('id', $v['material_id'])->first();
                    if (! empty($m_amount)) {
                        Material::query()->where('id', $v['material_id'])
                            ->update(['amount' => DB::Raw("amount-".(int) $v['amount'])]);
                    }
                }
            }
        }
        //添加日志流程
        $data = WorkflowProcess::query()->where('apply_id', $id)->where(
            'apply_key',
            'akbus_material_tyre_out'
        )->update([
            'node_id'    => $node_id, 'status' => $params['status'], 'reason' => $reason,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        // 4、记录流程日志
        $signature = isset($params['sign']) ? $params['sign'] : null;
        $result_name='审核';
        if($params['status'] == 1){
            $result_name='保存';
        }elseif($params['status'] == 2){
            if($params['node_id']==26){
                $result_name='提交';
            }else{
                $result_name='审核';
            }
        }elseif($params['status'] == 4){
            $result_name='审核不通过';
        }
        WorkflowLog::query()->insertGetId([
            'apply_id'  => $id, 'apply_key' => 'akbus_material_tyre_out', 'node_id' => $params['node_id'],
            'status'    => $params['status'],'result_name'=>$result_name, 'reason' => $reason, 'created_at' => date('Y-m-d H:i:s'),
            'signature' => $signature,
        ]);
        //发送消息通知
        $putInfo = TyreOutMaterial::query()->where('id', $id)->first();
        $user_name = User::where('id', $putInfo['user_id'])->value('name');
        $description = '物资轮胎出库-'.$user_name.PHP_EOL.
                        '单号：'.$putInfo['odd_num'].PHP_EOL.
                        '时间：'.date('Y-m-d', strtotime($putInfo['out_time']));
        $json=$this->ding->userNotify($node_id,'akbus_material_tyre_out',$id,$description);
        $result = $data ? true : false;
        return response()->formatJson(['result' => $result]);
    }

    /**
     * 轮胎出库统计列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function tyreOutMaterialStatiList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getTyreOutMaterialStatiList($params)
            ->groupBy('d.bus_num')->get()->toArray();
        if ($data) {
            $data = $this->outStatiTransData($data);
        }
        $dataCount = $this->getTyreOutMaterialStatiList($countParams)->groupBy('d.bus_num')->groupBy('d.material_id')->count();
        //每条线路
        $line = DB::table('akbus_bus_distribution')
            ->groupBy('line')->get()->toArray();
        //物资名称
        $material = DB::table('akbus_material')->get()->toArray();
        return response()->formatJson([
            'result' => $data, 'count' => $dataCount, 'line' => $line, 'material' => $material,
        ]);
    }

    public function getTyreOutMaterialStatiList($params)
    {
        $query = DB::table('akbus_material_tyre_out_detail as d')
            ->leftJoin('akbus_material_tyre_out as t', 't.id', '=', 'd.tyre_out_id')
            ->leftJoin('akbus_workflow_process as w', 'w.apply_id', '=', 'd.tyre_out_id')
            ->leftJoin('akbus_material as m', 'd.material_id', '=', 'm.id')
            ->select(
                'd.line',
                'bus_num',
                'd.specs',
                't.fleet',
                'd.unit',
                'd.price',
                'm.title',
                'd.created_at',
                'd.updated_at',
                DB::raw("SUM(d.amount) as total_amount")
            )
            ->where('w.apply_key', 'akbus_material_tyre_out')
            ->where('w.status', 0);
        if (isset($params['material'])) {
            if (gettype($params['material']) == 'string') {
                $params['material'] = explode(',', $params['material']);
            }
            if (count($params['material']) > 0) {
                $query->whereIn('d.material_id', $params['material']);
            }
        }
        if (isset($params['line']) && $params['line'] !== "-1") {
            $query->where('d.line', $params['line']);
        }
        if (isset($params['fleet'])) {
            $query->where('t.fleet', 'like', '%'.$params['fleet'].'%');
        }
        if (isset($params['start_date_time'])) {
            $query->where('d.created_at', '>=', date('Y-m-d', strtotime($params['start_date_time'])));
        }
        if (isset($params['end_date_time'])) {
            $query->where('d.created_at', '<=', date('Y-m-d', strtotime($params['end_date_time'])));
        }
        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }
        return $query->orderByDesc('d.created_at');
    }

    public function tyreOutStatiTransData($data)
    {
        $units = Dict::getOptionsArrByName("物资单位");
        foreach ($data as $key => $v) {
            $data[$key]['unit'] = $units[$v['unit']];
            $data[$key]['total_price'] = $v['price'] * $v['total_amount'];
        }
        return $data;
    }

    /**
     *我发起的 出入库列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function myMaterialList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($params['pageNumber'], $params['pageSize']);
        $put_data = $this->getPutMaterialList($params)->get()->toArray();
        if ($put_data) {
            $put_data = $this->putTransData($put_data);
        }
        $out_data = $this->getOutMaterialList($params)->get()->toArray();
        if ($out_data) {
            $out_data = $this->outTransData($out_data);
        }
        $tyreOut_data = $this->getTyreOutMaterialList($params)->get()->toArray();
        if ($tyreOut_data) {
            $tyreOut_data = $this->tyreOutTransData($tyreOut_data);
        }
        $data = array_merge($put_data, $out_data, $tyreOut_data);
        $data = collect($data);
        if (isset($countParams['pageNumber']) && isset($countParams['pageSize'])) {
            $data = $data->forPage($countParams['pageNumber'], $countParams['pageSize']);
        }
        $data = $data->sortByDesc('created_at')->values()->toArray();
        $this->getSeeIds($params['ding_user_id']);
        $group_id = $this->roleId;
        $role_name = $this->roleName;
        return response()->formatJson([
            'personnel' => $data, 'role' => $group_id, 'role_name' => $role_name,
        ]);
    }
}
